/**
 * WMS主题配置系统
 *
 * 提供动态主题切换、主题定制和主题管理功能
 * 支持亮色、暗色、高对比度等多种主题模式
 */

import type { WmsThemeConfig } from "@/components/wms/types";

/**
 * 预定义主题配置
 */
export const WMS_THEMES: Record<string, WmsThemeConfig> = {
  // 默认亮色主题
  light: {
    name: "light",
    primaryColor: "#1890ff",
    successColor: "#52c41a",
    warningColor: "#faad14",
    dangerColor: "#ff4d4f",
    infoColor: "#1890ff",
    backgroundColor: "#ffffff",
    textColor: "#262626",
    borderColor: "#d9d9d9",
    fontSize: {
      small: "12px",
      medium: "14px",
      large: "16px",
      xlarge: "18px",
    },
    spacing: {
      xs: "4px",
      sm: "8px",
      md: "16px",
      lg: "24px",
      xl: "32px",
    },
  },

  // 暗色主题
  dark: {
    name: "dark",
    primaryColor: "#177ddc",
    successColor: "#49aa19",
    warningColor: "#d89614",
    dangerColor: "#d32029",
    infoColor: "#177ddc",
    backgroundColor: "#1f1f1f",
    textColor: "#ffffff",
    borderColor: "#424242",
    fontSize: {
      small: "12px",
      medium: "14px",
      large: "16px",
      xlarge: "18px",
    },
    spacing: {
      xs: "4px",
      sm: "8px",
      md: "16px",
      lg: "24px",
      xl: "32px",
    },
  },

  // 高对比度主题
  highContrast: {
    name: "high-contrast",
    primaryColor: "#0000ff",
    successColor: "#008000",
    warningColor: "#ff8c00",
    dangerColor: "#ff0000",
    infoColor: "#0000ff",
    backgroundColor: "#ffffff",
    textColor: "#000000",
    borderColor: "#000000",
    fontSize: {
      small: "12px",
      medium: "14px",
      large: "16px",
      xlarge: "18px",
    },
    spacing: {
      xs: "4px",
      sm: "8px",
      md: "16px",
      lg: "24px",
      xl: "32px",
    },
  },

  // 蓝色主题
  blue: {
    name: "blue",
    primaryColor: "#2196f3",
    successColor: "#4caf50",
    warningColor: "#ff9800",
    dangerColor: "#f44336",
    infoColor: "#2196f3",
    backgroundColor: "#ffffff",
    textColor: "#262626",
    borderColor: "#e0e0e0",
    fontSize: {
      small: "12px",
      medium: "14px",
      large: "16px",
      xlarge: "18px",
    },
    spacing: {
      xs: "4px",
      sm: "8px",
      md: "16px",
      lg: "24px",
      xl: "32px",
    },
  },

  // 绿色主题
  green: {
    name: "green",
    primaryColor: "#52c41a",
    successColor: "#52c41a",
    warningColor: "#faad14",
    dangerColor: "#ff4d4f",
    infoColor: "#13c2c2",
    backgroundColor: "#ffffff",
    textColor: "#262626",
    borderColor: "#d9d9d9",
    fontSize: {
      small: "12px",
      medium: "14px",
      large: "16px",
      xlarge: "18px",
    },
    spacing: {
      xs: "4px",
      sm: "8px",
      md: "16px",
      lg: "24px",
      xl: "32px",
    },
  },

  // 紫色主题
  purple: {
    name: "purple",
    primaryColor: "#722ed1",
    successColor: "#52c41a",
    warningColor: "#faad14",
    dangerColor: "#ff4d4f",
    infoColor: "#722ed1",
    backgroundColor: "#ffffff",
    textColor: "#262626",
    borderColor: "#d9d9d9",
    fontSize: {
      small: "12px",
      medium: "14px",
      large: "16px",
      xlarge: "18px",
    },
    spacing: {
      xs: "4px",
      sm: "8px",
      md: "16px",
      lg: "24px",
      xl: "32px",
    },
  },
};

/**
 * 密度模式配置
 */
export const WMS_DENSITY_MODES = {
  compact: {
    name: "compact",
    description: "紧凑模式",
    spacing: {
      xs: "2px",
      sm: "4px",
      md: "8px",
      lg: "12px",
      xl: "16px",
    },
    controlHeight: {
      small: "20px",
      medium: "24px",
      large: "28px",
    },
  },
  default: {
    name: "default",
    description: "默认模式",
    spacing: {
      xs: "4px",
      sm: "8px",
      md: "16px",
      lg: "24px",
      xl: "32px",
    },
    controlHeight: {
      small: "24px",
      medium: "32px",
      large: "40px",
    },
  },
  comfortable: {
    name: "comfortable",
    description: "舒适模式",
    spacing: {
      xs: "6px",
      sm: "12px",
      md: "24px",
      lg: "32px",
      xl: "48px",
    },
    controlHeight: {
      small: "32px",
      medium: "40px",
      large: "48px",
    },
  },
};

/**
 * 主题管理类
 */
export class WmsThemeManager {
  private currentTheme: string = "light";
  private currentDensity: string = "default";
  private customThemes: Map<string, WmsThemeConfig> = new Map();
  private themeChangeCallbacks: Set<(theme: string) => void> = new Set();

  constructor() {
    this.loadThemeFromStorage();
    this.applySystemTheme();
  }

  /**
   * 获取当前主题
   */
  getCurrentTheme(): string {
    return this.currentTheme;
  }

  /**
   * 获取当前密度模式
   */
  getCurrentDensity(): string {
    return this.currentDensity;
  }

  /**
   * 获取主题配置
   */
  getThemeConfig(themeName?: string): WmsThemeConfig {
    const name = themeName || this.currentTheme;
    return this.customThemes.get(name) || WMS_THEMES[name] || WMS_THEMES.light;
  }

  /**
   * 获取所有可用主题
   */
  getAvailableThemes(): Array<{ name: string; config: WmsThemeConfig }> {
    const themes = [];

    // 预定义主题
    for (const [name, config] of Object.entries(WMS_THEMES)) {
      themes.push({ name, config });
    }

    // 自定义主题
    for (const [name, config] of this.customThemes) {
      themes.push({ name, config });
    }

    return themes;
  }

  /**
   * 切换主题
   */
  setTheme(themeName: string): void {
    if (themeName === this.currentTheme) return;

    const themeConfig = this.getThemeConfig(themeName);
    if (!themeConfig) {
      console.warn(`主题 "${themeName}" 不存在`);
      return;
    }

    this.currentTheme = themeName;
    this.applyTheme(themeConfig);
    this.saveThemeToStorage();
    this.notifyThemeChange(themeName);
  }

  /**
   * 设置密度模式
   */
  setDensity(densityName: string): void {
    if (densityName === this.currentDensity) return;

    const densityConfig = WMS_DENSITY_MODES[densityName];
    if (!densityConfig) {
      console.warn(`密度模式 "${densityName}" 不存在`);
      return;
    }

    this.currentDensity = densityName;
    this.applyDensity(densityConfig);
    this.saveDensityToStorage();
  }

  /**
   * 注册自定义主题
   */
  registerTheme(name: string, config: WmsThemeConfig): void {
    this.customThemes.set(name, config);
  }

  /**
   * 移除自定义主题
   */
  removeTheme(name: string): void {
    if (WMS_THEMES[name]) {
      console.warn(`不能删除预定义主题 "${name}"`);
      return;
    }

    this.customThemes.delete(name);

    if (this.currentTheme === name) {
      this.setTheme("light");
    }
  }

  /**
   * 创建自定义主题
   */
  createCustomTheme(
    name: string,
    baseTheme: string,
    overrides: Partial<WmsThemeConfig>,
  ): void {
    const baseConfig = this.getThemeConfig(baseTheme);
    const customConfig: WmsThemeConfig = {
      ...baseConfig,
      ...overrides,
      name,
    };

    this.registerTheme(name, customConfig);
  }

  /**
   * 监听主题变化
   */
  onThemeChange(callback: (theme: string) => void): () => void {
    this.themeChangeCallbacks.add(callback);

    // 返回取消监听的函数
    return () => {
      this.themeChangeCallbacks.delete(callback);
    };
  }

  /**
   * 获取主题CSS变量
   */
  getThemeCSSVariables(themeName?: string): Record<string, string> {
    const config = this.getThemeConfig(themeName);

    return {
      "--wms-primary-color": config.primaryColor,
      "--wms-success-color": config.successColor,
      "--wms-warning-color": config.warningColor,
      "--wms-error-color": config.dangerColor,
      "--wms-info-color": config.infoColor,
      "--wms-bg-white": config.backgroundColor,
      "--wms-text-color-primary": config.textColor,
      "--wms-border-color": config.borderColor,
      "--wms-font-size-xs": config.fontSize.small,
      "--wms-font-size-sm": config.fontSize.medium,
      "--wms-font-size-md": config.fontSize.large,
      "--wms-font-size-lg": config.fontSize.xlarge,
      "--wms-spacing-xs": config.spacing.xs,
      "--wms-spacing-sm": config.spacing.sm,
      "--wms-spacing-md": config.spacing.md,
      "--wms-spacing-lg": config.spacing.lg,
      "--wms-spacing-xl": config.spacing.xl,
    };
  }

  /**
   * 导出主题配置
   */
  exportTheme(themeName?: string): string {
    const config = this.getThemeConfig(themeName);
    return JSON.stringify(config, null, 2);
  }

  /**
   * 导入主题配置
   */
  importTheme(themeData: string): void {
    try {
      const config: WmsThemeConfig = JSON.parse(themeData);
      this.registerTheme(config.name, config);
    } catch (error) {
      console.error("导入主题失败:", error);
      throw new Error("主题数据格式不正确");
    }
  }

  /**
   * 应用主题
   */
  private applyTheme(config: WmsThemeConfig): void {
    const root = document.documentElement;
    const variables = this.getThemeCSSVariables(config.name);

    // 设置CSS变量
    Object.entries(variables).forEach(([key, value]) => {
      root.style.setProperty(key, value);
    });

    // 设置主题属性
    root.setAttribute("data-theme", config.name);

    // 生成色彩变体
    this.generateColorVariants(config);
  }

  /**
   * 应用密度模式
   */
  private applyDensity(config: any): void {
    const root = document.documentElement;

    // 设置密度CSS变量
    Object.entries(config.spacing).forEach(([key, value]) => {
      root.style.setProperty(`--wms-spacing-${key}`, value);
    });

    Object.entries(config.controlHeight).forEach(([key, value]) => {
      root.style.setProperty(
        `--wms-form-control-height-${key === "medium" ? "base" : key}`,
        value,
      );
    });

    // 设置密度属性
    root.setAttribute("data-density", config.name);
  }

  /**
   * 生成色彩变体
   */
  private generateColorVariants(config: WmsThemeConfig): void {
    const root = document.documentElement;

    const colors = {
      primary: config.primaryColor,
      success: config.successColor,
      warning: config.warningColor,
      error: config.dangerColor,
      info: config.infoColor,
    };

    Object.entries(colors).forEach(([name, color]) => {
      const variants = this.generateColorShades(color);

      root.style.setProperty(`--wms-${name}-color`, color);
      root.style.setProperty(`--wms-${name}-color-light`, variants.light);
      root.style.setProperty(`--wms-${name}-color-lighter`, variants.lighter);
      root.style.setProperty(`--wms-${name}-color-dark`, variants.dark);
      root.style.setProperty(`--wms-${name}-color-darker`, variants.darker);
      root.style.setProperty(`--wms-${name}-color-hover`, variants.hover);
      root.style.setProperty(`--wms-${name}-color-active`, variants.active);
    });
  }

  /**
   * 生成颜色色阶
   */
  private generateColorShades(color: string): Record<string, string> {
    // 简化的颜色生成，实际项目中可以使用更复杂的颜色算法
    const hsl = this.hexToHsl(color);

    return {
      lighter: this.hslToHex(
        hsl.h,
        Math.max(0, hsl.s - 20),
        Math.min(100, hsl.l + 30),
      ),
      light: this.hslToHex(
        hsl.h,
        Math.max(0, hsl.s - 10),
        Math.min(100, hsl.l + 20),
      ),
      dark: this.hslToHex(
        hsl.h,
        Math.min(100, hsl.s + 10),
        Math.max(0, hsl.l - 15),
      ),
      darker: this.hslToHex(
        hsl.h,
        Math.min(100, hsl.s + 20),
        Math.max(0, hsl.l - 30),
      ),
      hover: this.hslToHex(hsl.h, hsl.s, Math.min(100, hsl.l + 10)),
      active: this.hslToHex(hsl.h, hsl.s, Math.max(0, hsl.l - 10)),
    };
  }

  /**
   * 应用系统主题偏好
   */
  private applySystemTheme(): void {
    if (
      window.matchMedia &&
      window.matchMedia("(prefers-color-scheme: dark)").matches
    ) {
      if (this.currentTheme === "light") {
        this.setTheme("dark");
      }
    }

    // 监听系统主题变化
    window
      .matchMedia("(prefers-color-scheme: dark)")
      .addEventListener("change", (e) => {
        if (e.matches && this.currentTheme === "light") {
          this.setTheme("dark");
        } else if (!e.matches && this.currentTheme === "dark") {
          this.setTheme("light");
        }
      });
  }

  /**
   * 从存储加载主题
   */
  private loadThemeFromStorage(): void {
    try {
      const theme = localStorage.getItem("wms-theme");
      const density = localStorage.getItem("wms-density");

      if (theme) {
        this.currentTheme = theme;
      }

      if (density) {
        this.currentDensity = density;
      }
    } catch (error) {
      console.warn("加载主题配置失败:", error);
    }
  }

  /**
   * 保存主题到存储
   */
  private saveThemeToStorage(): void {
    try {
      localStorage.setItem("wms-theme", this.currentTheme);
    } catch (error) {
      console.warn("保存主题配置失败:", error);
    }
  }

  /**
   * 保存密度模式到存储
   */
  private saveDensityToStorage(): void {
    try {
      localStorage.setItem("wms-density", this.currentDensity);
    } catch (error) {
      console.warn("保存密度配置失败:", error);
    }
  }

  /**
   * 通知主题变化
   */
  private notifyThemeChange(theme: string): void {
    this.themeChangeCallbacks.forEach((callback) => {
      try {
        callback(theme);
      } catch (error) {
        console.error("主题变化回调执行失败:", error);
      }
    });
  }

  /**
   * 颜色转换工具方法
   */
  private hexToHsl(hex: string): { h: number; s: number; l: number } {
    // 简化的HSL转换实现
    const r = parseInt(hex.slice(1, 3), 16) / 255;
    const g = parseInt(hex.slice(3, 5), 16) / 255;
    const b = parseInt(hex.slice(5, 7), 16) / 255;

    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    let h = 0;
    let s = 0;
    const l = (max + min) / 2;

    if (max === min) {
      h = s = 0;
    } else {
      const d = max - min;
      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

      switch (max) {
        case r:
          h = (g - b) / d + (g < b ? 6 : 0);
          break;
        case g:
          h = (b - r) / d + 2;
          break;
        case b:
          h = (r - g) / d + 4;
          break;
      }
      h /= 6;
    }

    return { h: h * 360, s: s * 100, l: l * 100 };
  }

  private hslToHex(h: number, s: number, l: number): string {
    h = h / 360;
    s = s / 100;
    l = l / 100;

    const hue2rgb = (p: number, q: number, t: number) => {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    };

    let r, g, b;

    if (s === 0) {
      r = g = b = l;
    } else {
      const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      const p = 2 * l - q;
      r = hue2rgb(p, q, h + 1 / 3);
      g = hue2rgb(p, q, h);
      b = hue2rgb(p, q, h - 1 / 3);
    }

    const toHex = (c: number) => {
      const hex = Math.round(c * 255).toString(16);
      return hex.length === 1 ? "0" + hex : hex;
    };

    return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
  }
}

// 创建全局主题管理器实例
export const wmsThemeManager = new WmsThemeManager();

// Vue插件安装函数
export function setupTheme(app: any) {
  // 注入主题管理器
  app.config.globalProperties.$theme = wmsThemeManager;
  app.provide("theme", wmsThemeManager);

  // 初始化主题
  const currentTheme = wmsThemeManager.getCurrentTheme();
  const currentDensity = wmsThemeManager.getCurrentDensity();

  wmsThemeManager.setTheme(currentTheme);
  wmsThemeManager.setDensity(currentDensity);
}
